<?php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// 加载字典文件
$dictionary = [];
if (file_exists('dictionary.json')) {
    $dictionary = json_decode(file_get_contents('dictionary.json'), true) ?? [];
}

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $type = $_POST['type'] ?? '';
                $key = $_POST['key'] ?? '';
                $value = $_POST['value'] ?? '';
                
                if (empty($type) || empty($key) || empty($value)) {
                    echo json_encode(['success' => false, 'message' => '所有字段都必须填写']);
                    exit();
                }
                
                if (!isset($dictionary[$type])) {
                    $dictionary[$type] = [];
                }
                
                $dictionary[$type][$key] = $value;
                break;
                
            case 'edit':
                $type = $_POST['type'] ?? '';
                $key = $_POST['key'] ?? '';
                $value = $_POST['value'] ?? '';
                
                if (empty($type) || empty($key) || empty($value)) {
                    echo json_encode(['success' => false, 'message' => '所有字段都必须填写']);
                    exit();
                }
                
                if (isset($dictionary[$type][$key])) {
                    $dictionary[$type][$key] = $value;
                }
                break;
                
            case 'delete':
                $type = $_POST['type'] ?? '';
                $key = $_POST['key'] ?? '';
                
                if (empty($type) || empty($key)) {
                    echo json_encode(['success' => false, 'message' => '参数不完整']);
                    exit();
                }
                
                if (isset($dictionary[$type][$key])) {
                    unset($dictionary[$type][$key]);
                }
                break;
        }
        
        // 保存字典文件
        if (file_put_contents('dictionary.json', json_encode($dictionary, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => '保存失败']);
        }
        exit();
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>字典维护</title>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .section {
            margin-bottom: 30px;
        }
        .section-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary {
            background-color: #1677ff;
            color: white;
        }
        .btn-danger {
            background-color: #ff4d4f;
            color: white;
        }
        .btn:hover {
            opacity: 0.8;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .table th, .table td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .table th {
            background-color: #fafafa;
        }
        .action-btn {
            padding: 4px 8px;
            margin: 0 4px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .back-btn {
            color: #1677ff;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
        }
        .back-btn:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>字典维护</h2>
            <a href="index.php" class="back-btn">返回首页</a>
        </div>

        <div class="section">
            <div class="section-title">添加字典项</div>
            <div class="form-group">
                <label>类型：</label>
                <select id="add-type" class="form-control">
                    <option value="tables">数据表</option>
                    <option value="fields">字段</option>
                    <option value="factory_codes">工厂编号</option>
                </select>
            </div>
            <div class="form-group">
                <label>键名：</label>
                <input type="text" id="add-key" class="form-control" placeholder="输入键名">
            </div>
            <div class="form-group">
                <label>值：</label>
                <input type="text" id="add-value" class="form-control" placeholder="输入值">
            </div>
            <button class="btn btn-primary" onclick="addDictionary()">添加</button>
        </div>

        <div class="section">
            <div class="section-title">字典列表</div>
            <div id="dictionary-list">
                <?php foreach ($dictionary as $type => $items): ?>
                <div class="section">
                    <h3><?php echo ucfirst($type); ?></h3>
                    <table class="table">
                        <tr>
                            <th>键名</th>
                            <th>值</th>
                            <th>操作</th>
                        </tr>
                        <?php foreach ($items as $key => $value): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($key); ?></td>
                            <td><?php echo htmlspecialchars($value); ?></td>
                            <td>
                                <button class="action-btn btn-primary" onclick="editDictionary('<?php echo $type; ?>', '<?php echo $key; ?>', '<?php echo $value; ?>')">编辑</button>
                                <button class="action-btn btn-danger" onclick="deleteDictionary('<?php echo $type; ?>', '<?php echo $key; ?>')">删除</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </table>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Toast提示框 -->
    <div id="toast" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:9999;min-width:180px;padding:18px 32px;background:rgba(0,0,0,0.85);color:#fff;border-radius:8px;font-size:18px;box-shadow:0 2px 12px rgba(0,0,0,0.18);text-align:center;pointer-events:none;transition:all 0.3s;"></div>

    <script>
        function addDictionary() {
            const type = document.getElementById('add-type').value;
            const key = document.getElementById('add-key').value;
            const value = document.getElementById('add-value').value;

            if (!type || !key || !value) {
                showToast('请填写所有字段', 'error');
                return;
            }

            fetch('dictionary_manage.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=add&type=${encodeURIComponent(type)}&key=${encodeURIComponent(key)}&value=${encodeURIComponent(value)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('添加成功', 'success');
                    location.reload();
                } else {
                    showToast(data.message || '添加失败', 'error');
                }
            })
            .catch(error => {
                showToast('操作失败：' + error.message, 'error');
            });
        }

        function editDictionary(type, key, value) {
            const newValue = prompt('请输入新的值：', value);
            if (newValue === null) return;

            fetch('dictionary_manage.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=edit&type=${encodeURIComponent(type)}&key=${encodeURIComponent(key)}&value=${encodeURIComponent(newValue)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('修改成功', 'success');
                    location.reload();
                } else {
                    showToast(data.message || '修改失败', 'error');
                }
            })
            .catch(error => {
                showToast('操作失败：' + error.message, 'error');
            });
        }

        function deleteDictionary(type, key) {
            if (!confirm('确定要删除这条记录吗？')) return;

            fetch('dictionary_manage.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=delete&type=${encodeURIComponent(type)}&key=${encodeURIComponent(key)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('删除成功', 'success');
                    location.reload();
                } else {
                    showToast(data.message || '删除失败', 'error');
                }
            })
            .catch(error => {
                showToast('操作失败：' + error.message, 'error');
            });
        }

        function showToast(msg, type) {
            var toast = document.getElementById('toast');
            toast.innerText = msg;
            toast.style.background = type === 'error' ? 'rgba(255,77,79,0.95)' : 'rgba(0,0,0,0.85)';
            toast.style.display = 'block';
            clearTimeout(window.toastTimer);
            window.toastTimer = setTimeout(function(){ toast.style.display = 'none'; }, 3000);
        }
    </script>
</body>
</html> 